import threading
import logging

FORMAT = "%(thread)d %(threadName)s %(message)s"
logging.basicConfig(level=logging.INFO, format=FORMAT)


def worker(barrier: threading.Barrier):
    logging.info('n_waiting is {}'.format(barrier.n_waiting))
    try:
        bid = barrier.wait()
        logging.info('after barrier is {}'.format(bid))
    except threading.BrokenBarrierError:
        logging.info('broken barrier is {}'.format(threading.current_thread().name))

# 初始化锁，路障为3
barrier = threading.Barrier(3)

for i in range(6):
    threading.Thread(target=worker, args=(barrier,)).start()

"""
从运行结果看出：
所有线程冲到了barrier前等待，直到线程数达到barrier设置的parties数量，barrier才会开放，这时等待的线程会开始执行，执行完毕后barrier再次关闭，直到下一批线程数达到barrier设置的parties数量，周而复始。
所以这里，执行的线程数一定要是barrier设置的parties数量的倍数。
"""